package com.xci.sys.controller;


import com.xci.core.annotation.Authorize;
import com.xci.core.base.RestMessage;
import com.xci.core.base.WebController;
import com.xci.core.exceptions.EntityNotFoundException;
import com.xci.core.helper.ConvertHelper;
import com.xci.core.helper.ExcelHelper;
import com.xci.core.helper.Helper;
import com.xci.core.helper.TreeHelper;
import com.xci.core.internal.Const;
import com.xci.core.web.JsonGrid;
import com.xci.core.web.TreeNode;
import com.xci.core.web.TreeNodeIndex;
import com.xci.sys.entity.SysModule;
import com.xci.sys.filter.ModuleFilter;
import com.xci.sys.service.ModuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统模块控制器
 */
@Authorize
@Slf4j
@Controller
@RequestMapping("/sys/module")
public class ModuleController extends WebController {
    @Resource
    private ModuleService moduleService;//模块服务

    //region 页面视图

    /**
     * 模块首页
     */
    @GetMapping
    @Authorize(code = "SystemModule")
    public String index() {
        return "sys/module/index";
    }

    /**
     * 模块新建页面
     */
    @GetMapping("/create")
    @Authorize(code = "SystemModule.Create")
    public String create(String parentId, ModelMap map) {
        createMark(map);
        SysModule entity = new SysModule();
        entity.setId(Helper.nextIdStr());
        entity.setParentId(parentId);
        entity.setStatus(true);
        entity.setIsExpand(true);
        entity.setIsMenu(true);
        entity.setIsPublic(false);
        map.put("entity", entity);
        map.put("parentName", getParentName(parentId));
        return "sys/module/edit";
    }

    /**
     * 模块编辑页面
     */
    @GetMapping("/edit")
    @Authorize(code = "SystemModule.Edit")
    public String edit(String id, ModelMap map) {
        SysModule entity = moduleService.selectById(id);
        if (entity == null) throw new EntityNotFoundException(id);
        map.put("entity", entity);
        map.put("parentName", getParentName(entity.getParentId()));
        return "sys/module/edit";
    }

    private String getParentName(String id) {
        String parentName = Const.EMPTY;
        if (Helper.isNotBlank(id) && !id.equals(Const.ROOT_NODE_ID)) {
            var parentModel = moduleService.selectById(id);
            if (parentModel!=null){
                parentName =parentModel.getName();
            }
        }
        if (Helper.isBlank(parentName)) {
            parentName = "顶层模块";
        }
        return parentName;
    }

    /**
     * 模块详细页面
     */
    @GetMapping("/details")
    public String details(String id, ModelMap map) {
        SysModule entity = moduleService.selectById(id);
        if (entity == null) throw new EntityNotFoundException(id);
        map.put("entity", entity);
        return "sys/module/details";
    }

    //endregion

    //region 数据处理

    /**
     * 模块表格数据
     */
    @ResponseBody
    @GetMapping("/grid")
    @Authorize(code = "SystemModule.Search")
    public JsonGrid grid(ModuleFilter filter) {
        List<SysModule> list = moduleService.selectList(filter);

        for (var item : list) {
            boolean hasChild = list.stream().anyMatch(p -> p.getParentId().equals(item.getId()));
            // item.setLeaf(hasChild ? 0 : 1);
            String state = "open";
            if (!item.getIsExpand() && hasChild) {
                state = "closed";
            }
            item.setState(state);
        }
        return RestMessage.grid(list);
    }

    /**
     * 保存模块
     */
    @ResponseBody
    @PostMapping("/createSave")
    @Authorize(code = "SystemModule.Create")
    public RestMessage createSave(@ModelAttribute SysModule entity) {
        return moduleService.insert(entity);
    }

    /**
     * 保存模块
     */
    @ResponseBody
    @PostMapping("/updateSave")
    @Authorize(code = "SystemModule.Edit")
    public RestMessage updateSave(@ModelAttribute SysModule entity) {
        return moduleService.update(entity);
    }

    /**
     * 保存拖拽数据(父节点和路径)
     */
    @ResponseBody
    @PostMapping("/dnd")
    @Authorize(code = "SystemModule.Drag")
    public RestMessage dnd(@RequestBody List<TreeNodeIndex> nodeIndexs) {
        return moduleService.batchUpdate(TreeHelper.toPrimaryKeyValues(nodeIndexs));
    }

    /**
     * 修改模块启用状态
     */
    @ResponseBody
    @PostMapping("/status")
    @Authorize(code = "SystemModule.Status")
    public RestMessage status(String id, Integer status) {
        return moduleService.updateStatus(id, ConvertHelper.toBool(status));
    }

    /**
     * 删除模块
     */
    @ResponseBody
    @PostMapping("/delete")
    @Authorize(code = "SystemModule.Delete")
    public RestMessage delete(String id) {
        return moduleService.delete(id);
    }

    /**
     * 导出模块
     */
    @GetMapping("/export")
    @Authorize(code = "SystemModule.Export")
    public void export(ModuleFilter filter) {
        ExcelHelper.exportWeb(moduleService.selectList(filter), SysModule.class, "系统模块");
    }

    //endregion
}
